package com.RHECmap.com;

import geofencing.*;

import java.io.IOException;
import java.security.PublicKey;
import java.text.BreakIterator;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.R.color;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;

import com.RHECmap.com.selfMap.RouteOverlay;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;


public class mapShow extends MapActivity{

	private MapView mapView;
	private MapController map_controller;
	private GeoPoint point =null;
	private boolean myLoc = false;
	private boolean elephantLoc = false;
	private List<Overlay> OverlayList;
	private boolean gps_status = false;	
	private MyLocationOverlay myLocationOverlay;
	private ItemizedOverlay itemizedoverlay;
	private String addressString = "Not address found";
	private boolean isPotentialLongPress;
	private TextView speed;
	private TextView date;
	private RouteOverlay route;
	public ArrayList<GeoPoint> geopoint;
	
	
	protected void onCreate(Bundle icicle) {	
		super.onCreate(icicle);
		setContentView(R.layout.showmap);	
		//Data.c = getApplicationContext(); 
	
		
		speed = (TextView) findViewById(R.id.textView1);
		speed.setText("0.0 kmh-1");
		
		String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
		date = (TextView) findViewById(R.id.textView2);
		date.setText(currentDateTimeString);
		
		mapView = (MapView)findViewById(R.id.map_view);	   
	    mapView.setBuiltInZoomControls(true);	
	    map_controller = mapView.getController();	   
	    map_controller.setZoom(18); 	    
	
	    
	    LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        LocationListener mlocListener = new MyLocationListener();
        mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
        
        geopoint=new ArrayList<GeoPoint>();
        
        mapView.setOnTouchListener(new OnTouchListener() {			

			public boolean onTouch(View view, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP) {
					
					if(Preferece.getMyStringPref(getApplicationContext(), "mark").equals("pressed")){
					  GeoPoint p = mapView.getProjection().fromPixels((int) event.getX(),(int) event.getY());
					  	
					  //Toast.makeText(getApplicationContext(), ""+p.getLatitudeE6() / 1E6+","+p.getLongitudeE6() /1E6, Toast.LENGTH_LONG).show();
					 if(geopoint.size()<=3){
						 
						 geopoint.add(p);	
					  
					 }
					 else {
						setFence(geopoint);
					}
					 
		        }//if
				}
				
				return true;
			}
		});
       
        //reset the flag
        
        Preferece.setMyString(getApplicationContext(), "mark", "unpressed");
	}
	
	
	
	//-- set the sketch of the fence
	private void setFence(ArrayList<GeoPoint> g){
		GeoPoint point = null;
		/*for(int i=0;i<g.size();i++){
			
			point=g.get(i);
			Toast.makeText(getApplicationContext(), "EXE:"+point.getLatitudeE6() / 1E6+","+point.getLongitudeE6() /1E6, Toast.LENGTH_LONG).show();
		}*/
		
		
		
		if(!(OverlayList==null)){


			//GeoPoint point = null;
			for(int i=0;i<g.size();i++){				
				point=g.get(i);
				
				Drawable drawable = this.getResources().getDrawable(R.drawable.location);
				itemizedoverlay = new ItemizedOverlay(drawable, this);
				OverlayItem overlayitem = new OverlayItem(point,"", "");
				itemizedoverlay.addOverlay(overlayitem);
				Log.e(null, "Before");				
				OverlayList.add(itemizedoverlay);
				Log.e(null, "After");				
								
			}
			
		}
		else {
			Toast.makeText( getApplicationContext(),"Execute Else",Toast.LENGTH_SHORT).show();
		}
		
	}
	

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {	
		MenuInflater inflater = getMenuInflater();
		if(Preferece.getMyStringPref(getApplicationContext(), "menu").equals("main")){
	    inflater.inflate(R.menu.menu, menu);
		}
		else{
			inflater.inflate(R.menu.setfence, menu);
		}
	    return true;
	}
	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		if(Preferece.getMyStringPref(getApplicationContext(), "menu").equals("main")){
			//if user select show current location
		
			if(item.getItemId() == R.id.sattelite){		
			      
				mapView.setSatellite(true);	  
			}
			else if(item.getItemId() == R.id.Street){				
				mapView.setSatellite(false);			
			}
			else if(item.getItemId() == R.id.mylocation){
			
					if(myLoc == false && elephantLoc == false){
						if(gps_status == false){
							turnGPSOn();
							gps_status =true;
						}					
						myLoc = true;					
						set_overlay();
					}
					else if(myLoc == false && elephantLoc == true){
						if(gps_status == false){
							turnGPSOn();
							gps_status =true;
						}					
						myLoc = true;			
					}
				
					else if(myLoc == true && elephantLoc == true){
						if(gps_status == false){
							turnGPSOn();
							gps_status =true;
						}					
						myLoc = false;	
						OverlayList.clear();
						mapView.invalidate();
						set_overlay();
						get_elephant_data();
					}
					else if(myLoc == true && elephantLoc == false){
						if(gps_status == true){
							turnGPSOff();
							gps_status = false;
						}
						myLoc = false;
						OverlayList.clear();
				
					
					}
			} 
			else if(item.getItemId() == R.id.elephantlocation){		
				if(myLoc == false && elephantLoc == false){
					set_overlay();	
					get_elephant_data();
				}
				else if(myLoc == true && elephantLoc == false){
					get_elephant_data();
				}
				else if(myLoc == false && elephantLoc == true){
					elephantLoc = false;
					OverlayList.clear();
					mapView.invalidate();
				}
				else if(myLoc == true && elephantLoc == true){
					OverlayList.clear();
					set_overlay();
					elephantLoc = false;
					mapView.invalidate();
					myLocationOverlay.enableMyLocation();	
				}
		
			
			}
			
	
			return true;
	}//end of if
		
		else{
			//if user select set fence from main menu
			
			if(item.getItemId()==R.id.mark){	
				set_overlay();
				Preferece.setMyString(getApplicationContext(), "mark", "pressed");
			}
			else if(item.getItemId()==R.id.remove){
				//call remove mathod
			}
			else {
				//call show method
			}
			
			return true;
			
			
		}//end of else
		
		
	}
	
	
	
	
	
	



	private void get_elephant_data(){
		List<GeoPoint> gp = new ArrayList<GeoPoint>();
		GeoPoint point1 = new GeoPoint((int)(6.91487420296234 * 1E6), (int)(79.9732575683826 * 1E6));
		GeoPoint point2 = new GeoPoint((int)(6.91429666666667 * 1E6), (int)(79.972255 * 1E6));
		GeoPoint point3 = new GeoPoint((int)(6.91283 * 1E6), (int)(79.9722583333333 * 1E6));	
		GeoPoint point4 = new GeoPoint((int)(6.91308046809007 * 1E6), (int)(79.9658809458963 * 1E6));	
		
		gp.add(point1); 
		gp.add(point2);     
		gp.add(point3); 	
		gp.add(point4); 	
		set_elephants_location(gp);
		elephantLoc = true;
	}

	
	
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		if(gps_status == true){
			turnGPSOff();
		}
		finish();
	}
	
	private void set_overlay(){
		myLocationOverlay = new MyLocationOverlay(this,mapView);
		myLocationOverlay.enableCompass(); 			
		OverlayList = mapView.getOverlays();  
		OverlayList.add(myLocationOverlay);  			
	}
	
	
	 public class MyLocationListener implements LocationListener

	    {
			public void onLocationChanged(Location loc) {			  
				 	
				 	double c_Latitud = loc.getLatitude();
				 	double c_Longitud = loc.getLongitude();
				 	double c_speed = loc.getSpeed();
				 	speed.setText(String.valueOf(c_speed)+ " " + "kmh-1");
				 	point = new GeoPoint((int)(c_Latitud * 1E6), (int)(c_Longitud * 1E6));				 	
				 	
				 	if(myLoc == true){					 		
				 		myLocationOverlay.enableMyLocation();			 		
				 		map_controller.animateTo(point);	
				 		
				 	}
				 
			}

			public void onProviderDisabled(String provider) {
				
				//	Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
					
				
			}

			public void onProviderEnabled(String provider) {
				
			//		Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
					
				
			}

			public void onStatusChanged(String provider, int status, Bundle extras) {
				// TODO Auto-generated method stub
				
			}
	    	
	    }
	 
	 
	
	 
	
	 
	 private void set_elephants_location(List<GeoPoint> gp){
		 
		 if(!(OverlayList == null)){			
			GeoPoint point = null;				
			for(int i = 0; i<gp.size(); i++ ){ 
			point = gp.get(i);		
			
			double lat = point.getLatitudeE6()/1E6;
			double lon = point.getLongitudeE6()/1E6;
			String address = getAddress(lat, lon);
			
			Drawable drawable = this.getResources().getDrawable(R.drawable.location);		
			itemizedoverlay = new ItemizedOverlay(drawable, this); 	
			OverlayItem overlayitem = new OverlayItem(point, "Name : " + "Test","Locaton : " + point + "\n" + address);	        	         
	        itemizedoverlay.addOverlay(overlayitem);
	        OverlayList.add(itemizedoverlay);	
	        myLocationOverlay.enableCompass(); 	
	        map_controller.animateTo(point);
	        
			} 
		 }
		 else{
			 Toast.makeText( getApplicationContext(),"Show My Location",Toast.LENGTH_SHORT).show();
		 }
			 
		 
	 }
	
	 
	 
	 private void turnGPSOn(){
	        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 
	        
	        if(!provider.contains("gps")){ //if gps is disabled 
	            final Intent poke = new Intent(); 
	            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");  
	            poke.addCategory(Intent.CATEGORY_ALTERNATIVE); 
	            poke.setData(Uri.parse("3"));  
	            sendBroadcast(poke); 
	            gps_status = true; 
	            }

	    }
	
	    private void turnGPSOff(){
	    	
	    	String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 
	    	 
	        if(provider.contains("gps")){ //if gps is enabled 
	            final Intent poke = new Intent(); 
	            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
	            poke.addCategory(Intent.CATEGORY_ALTERNATIVE); 
	            poke.setData(Uri.parse("3"));  
	            sendBroadcast(poke); 
	            gps_status = false;
	        }     	
	      } 
	    
	    
	    public String getAddress(double lat, double lng) {	    	
	      
	        Geocoder gc = new Geocoder(this, Locale.getDefault());
            try {
                List<Address> addresses = gc.getFromLocation(lat, lng, 3);
                StringBuilder sb = new StringBuilder();

                if (addresses.size() > 0) {
                    Address address = addresses.get(0);

                    for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                        sb.append(address.getAddressLine(i)).append("\n");

                    	sb.append(address.getCountryName());
                }
                addressString = sb.toString();
                
             //   Toast.makeText( getApplicationContext(),addressString,Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
            	
            }
            return addressString;
	    }



		
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
	    
 public class FenceOverlay extends com.google.android.maps.ItemizedOverlay<OverlayItem> {
	 public FenceOverlay(Drawable defaultMarker) {
		super(defaultMarker);
		
	}

	private Context context;
	 private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();		    
	 
	

	@Override
	public boolean onTouchEvent(MotionEvent arg0, MapView arg1) {
		Toast.makeText( context,"Praveen",Toast.LENGTH_SHORT).show();
		return true;
	}
	 
	public void addOverlay(OverlayItem overlay) {
		mapOverlays.add(overlay);
		this.populate();
		
	}

	@Override
	protected OverlayItem createItem(int i) {
		return mapOverlays.get(i);
	}

	@Override
	public int size() {
		 return mapOverlays.size();
	}
    	
 }
	    
	    
/*	


		@Override
		public boolean dispatchTouchEvent(MotionEvent event) {
			handleLongPress(event);
		//	Toast.makeText( getApplicationContext(),"Praveen",Toast.LENGTH_SHORT).show();
			return super.dispatchTouchEvent(event);
		}


		private void handleLongPress(MotionEvent event) {
			 if (event.getAction() == MotionEvent.ACTION_POINTER_DOWN) {
		            // A new touch has been detected
		 
		            new Thread(new Runnable() {
		                public void run() {
		                    Looper.prepare();
		                    if (isLongPressDetected()) {
		                    	Toast.makeText( getApplicationContext(),"Praveen",Toast.LENGTH_SHORT).show();
		             
		                    }
		                }
		            }).start();
		        } 
		}
	    
	    
		public boolean isLongPressDetected() {
	        isPotentialLongPress = true;
	        try {
	            for (int i = 0; i < (50); i++) {
	                Thread.sleep(10);
	                if (!isPotentialLongPress) {
	                    return false;
	                }
	            }
	            return true;
	        } catch (InterruptedException e) {
	            return false;
	        } finally {
	            isPotentialLongPress = false;
	        }
	    }
	        
	    */
	   
	    
	    
}
